import { BrowserWindow, nativeTheme, dialog, app } from 'electron';
import path from 'path';
import icon from '@assets/icon.png?asset'


import {
  WINDOW_HEIGHT,
  WINDOW_WIDTH,
  WINDOW_MIN_HEIGHT
} from '@shared/constans/common';


export default () => {
  let win: any;
  let isQuitting = false;

  const init = () => {
    createWindow();
  };

  const createWindow = async () => {
    win = new BrowserWindow({
      height: WINDOW_HEIGHT,
      minHeight: WINDOW_MIN_HEIGHT,
      useContentSize: true,
      resizable: true,
      width: WINDOW_WIDTH,
      title: 'Lazisoft',
      autoHideMenuBar: true,
      ...(process.platform === 'linux' ? { icon } : {}),
      backgroundColor: nativeTheme.shouldUseDarkColors ? '#1c1c28' : '#fff',
      webPreferences: {
        webSecurity: false,
        backgroundThrottling: false,
        contextIsolation: false,
        webviewTag: true,
        nodeIntegration: true,
        preload: path.join(__dirname, '../preload/index.js'),
        spellcheck: false,
        sandbox: false
      },
    });

    if (process.env.NODE_ENV === 'development') {
      // Load the url of the dev server if in development mode
      win.loadURL("http://localhost:5173/");
    } else {
      win.loadURL('app://bundle/../renderer/index.html');
    }

    win.on('closed', () => {
      win.removeAllListeners();
      win = undefined;
    });

    win.on("close", (e: Event) => {
      if (!isQuitting) {
        e.preventDefault();
        dialog.showMessageBox(win, {
          type: 'question',
          buttons: ['最小化到托盘', '退出'],
          title: '关闭提示',
          message: '您想要最小化到托盘还是退出应用？',
        }).then((dialogResult) => {
          if (dialogResult.response === 0) {
            win.hide()
          } else {
            isQuitting = true;
            app.quit();
          }
        });
      } else {
        app.quit()
      }
    })

    win.on('show', () => {
      // versonHandler.checkUpdate();
      // win.webContents.openDevTools();
    });

    win.on('hide', () => {

    });

  };

  const getWindow = () => win;
  const getIsQuitting = () => isQuitting;
  const setQuitting = (status: boolean) => { isQuitting = status; }

  return {
    init,
    getWindow,
    getIsQuitting,
    setQuitting,
  };
};
